package user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import core.domain.ListDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import user.domain.question.Question;
import user.domain.question.dto.QuestionQueryDTO;
import user.domain.question.es.QuestionES;
import user.domain.question.vo.QuestionDetailVO;
import user.domain.question.vo.QuestionVO;
import user.domain.question.vo.RankVO;
import user.es.QuestionRepository;
import user.manager.QuestionCacheManage;
import user.mapper.CQuestionMapper;
import user.mapper.UserSubmitMapper;
import user.service.IQuestionService;

import java.util.ArrayList;
import java.util.List;

@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private CQuestionMapper cQuestionMapper;

    @Autowired
    private QuestionCacheManage questionCacheManage;

    @Autowired
    private UserSubmitMapper userSubmitMapper;
    @Override
    public ListDataInfo list(QuestionQueryDTO questionQueryDTO) {
        long count = questionRepository.count();
        if(count <= 0){
            refreshQuestion();
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(questionQueryDTO.getPageNum() -1, questionQueryDTO.getPageSize(), sort);
        Integer difficulty = questionQueryDTO.getDifficulty();
        String keyword = questionQueryDTO.getKeyword();

        Page<QuestionES> page;
        if(difficulty == null && StrUtil.isEmpty(keyword)){ // 难度和关键字都为空
            page = questionRepository.findAll(pageable);  // 查询所有
        } else if (StrUtil.isEmpty(keyword)){  // 关键字为空
            page = questionRepository.findQuestionByDifficulty(difficulty, pageable);   // 根据难度查询
        } else if (difficulty == null){  // 难度为空
            page = questionRepository.findByTitleOrContent(keyword, keyword, pageable); // 根据关键字查询
        } else {  // 难度和关键字都不为空
            page = questionRepository.findByTitleOrContentAndDifficulty(keyword, keyword, difficulty, pageable);
        }  // 根据难度和关键字同时查询
        long total = page.getTotalElements();
        if(total <= 0){
            return ListDataInfo.empty();
        }
//        List<QuestionES> content = page.getContent();
        List<QuestionVO> questionVOList = BeanUtil.copyToList(page.getContent(), QuestionVO.class);
        return ListDataInfo.success(questionVOList, (int) total);
    }

    @Override
    public QuestionDetailVO detail(Long questionId) {
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        if(questionES != null){
            BeanUtil.copyProperties(questionES, questionDetailVO);
            return questionDetailVO;
        }
        Question question = cQuestionMapper.selectById(questionId);
        if(question == null){
            return null;
        }
        refreshQuestion();
        BeanUtil.copyProperties(question, questionDetailVO);
        return questionDetailVO;
    }

    @Override
    public String preQuestion(Long questionId) {
        if(questionCacheManage.getQuestionCount() <= 0){
            questionCacheManage.refreshQuestion();
        }
        return questionCacheManage.preQuestion(questionId).toString();
    }

    @Override
    public String nextQuestion(Long questionId) {
        if(questionCacheManage.getQuestionCount() <= 0){
            questionCacheManage.refreshQuestion();
        }
        return questionCacheManage.nextQuestion(questionId).toString();
    }

    @Override
    public List<RankVO> topRank() {
        List<RankVO> res;
        if(questionCacheManage.getTopRankCount() <= 0){
            res = userSubmitMapper.selectTopFiveRank();
            if(CollectionUtil.isEmpty(res)){
                return null;
            }
            questionCacheManage.refreshTopRank(res);
        } else {
            res = questionCacheManage.topRank();
//            List<RankVO> tmp = res;
//            List<Long> questionIdList = questionCacheManage.topRank();
//            Iterable<QuestionES> allById = questionRepository.findAllById(questionIdList);
//            allById.forEach(questionES -> {
//                RankVO rankVO = new RankVO();
//                rankVO.setQuestionId(questionES.getQuestionId());
//                rankVO.setTitle(questionES.getTitle());
//                tmp.add(rankVO);
//            });
        }
        return res;
    }

    private void refreshQuestion() {
        List<Question> questionList = cQuestionMapper.selectList(new LambdaQueryWrapper<Question>());
        if(CollectionUtil.isEmpty(questionList)){
            return;
        }
        List<QuestionES> questionESList = BeanUtil.copyToList(questionList, QuestionES.class);
        questionRepository.saveAll(questionESList);
    }
}
